package algorithm.binarysearch;

/**
 * 二分查找算法 非递归方式
 * 递归方式参照数据结构包下面的search
 *
 * @author jack.wu
 * @version 1.0
 * @date 2020-04-04
 */
public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = {1, 8, 10, 11, 28, 33, 99};
        int target = 100;
        int index = binarySearch(arr, target);
        System.out.println("index = " + index);
    }

    /**
     * 二分查找 非递归方式
     *
     * @param arr    目标数组
     * @param target 需要查找的目标数
     * @return 目标数的下标
     */
    private static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }
}
